package peer.rdp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.util.LinkedList;
import java.util.Queue;

import peer.rdp.message.ConnectMessage1;
import peer.rdp.message.ConnectMessage2;
import peer.rdp.message.ConnectMessage3;


public class DatagramSocket2 {
	Route ro;
	private Queue<DatagramPacket> dpBuffer;
	DS2Ident di;
	public Connection conn;
	boolean exceptionThrow=false;
	boolean waitConnectMeassage=true;
	public DatagramSocket2(Route ro,DS2Ident di,Connection conn){
		this.ro=ro;
		this.di=di;
		this.conn=conn;
		dpBuffer=new LinkedList<DatagramPacket>();
	}
	
	Queue getBuffer(){
		return dpBuffer;
	}
	
	void send(DatagramPacket dp) throws IOException {
			ro.sendPacket(dp,di);
	}
	
	synchronized DatagramPacket receive() throws IOException, ConnectException {
		DatagramPacket dp=ro.getPacket(di);
		return dp;
	}
	
	void sendConnectMessage1(){
		//System.out.println("sendConnectMessage1 "+di.dstIp+" "+di.dstPort);
		ConnectMessage1 cm1=new ConnectMessage1();
		cm1.setDstAddress(di.dstIp);
		cm1.setDstPort(di.dstPort);
		try {
			send(cm1.getDatagramPacket());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	void sendConnectMessage3(){
		ConnectMessage3 cm3=new ConnectMessage3();
		cm3.setDstAddress(di.dstIp);
		cm3.setDstPort(di.dstPort);
		try {
			send(cm3.getDatagramPacket());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	void sendConnectMessage2() throws IOException{
		System.out.println("NNNNNNNNNN "+di.dstIp+" "+di.dstPort);
		ConnectMessage2 cm2=new ConnectMessage2();
		cm2.setDstAddress(di.dstIp);
		cm2.setDstPort(di.dstPort);
		send(cm2.getDatagramPacket());
	}
	
	void receiveConnectMessage2(InetAddress dstIp,int dstPort) throws ConnectException {
		peer.Config.route.receiveConnectMessage2(dstIp,dstPort);
	}
	
	void receiveConnectMessage3(DS2Ident di) throws Exception{
		peer.Config.route.receiveConnectMessage3(di);
	}
}
